<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="测量设备">
          <el-input
            v-model="searchParam.detectionEquipCode"
            placeholder="请输入测量设备"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="检测时间">
          <el-date-picker
            v-model="searchParam.detectionTimes"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getDate"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="excelBoxOpen">
          <template #icon><i-ep-upload /></template>导入</el-button
        >
        <el-dialog
          :close-on-click-modal="false"
          title="检测数据导入"
          v-model="excelBox"
          width="400px"
          @close="closeDialog"
        >
          <el-form
            ref="formRef"
            :model="formData"
            :inline="true"
            :rules="rules"
            label-width="100"
          >
            <el-row>
              <el-col :span="24">
                <el-form-item label="检具编号" prop="detectionEquipCode">
                  <el-input
                    v-model="formData.detectionEquipCode"
                    placeholder="请输入检具编号"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="零件编码" prop="partCode">
                  <el-input
                    v-model="formData.partCode"
                    placeholder="请输入零件编码"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="零件批次号" prop="partBatch">
                  <el-input
                    v-model="formData.partBatch"
                    placeholder="请输入零件批次号"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="文件" prop="file">
                  <div>
                    <input
                      :key="uploadKey"
                      class="crop-input"
                      type="file"
                      name="image"
                      ref="onload_exl"
                      @change="getfilepath"
                    />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" :loading="uploadLoading" @click="upload"
                >上 传</el-button
              >
              <el-button @click="closeDialog">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
      >
        <el-table-column
          v-for="(item, index) in props.cols"
          :key="index"
          :label="item.label"
          :prop="item.prop"
          :min-width="item.width"
          show-overflow-tooltip
          :align="item.align"
          header-align="center"
        />
        <el-table-column fixed="right" label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
            >
              <i-ep-search />
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <qddetectiondatamain-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :descriptions="props.descriptions"
      :detailCols="props.detailCols"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary, useDownload } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "COMMONQUALITYDATADB",
  inheritAttrs: false,
});

const props = defineProps({
  dataKind: {
    type: Number,
    required: true,
  },
  cols: {
    type: Array,
    required: true,
  },
  descriptions: {
    type: Array,
    required: true,
  },
  detailCols: {
    type: Array,
    required: true,
  },
});

// 导入excel
// const uploadApi = "/eam/eamfaultmode/upload";
const uploadApi = "/qms/qddetectiondatamain/upload";
const excelBox = ref(false);
const fileName = ref("");
const uploadKey = ref(Math.random());

function excelBoxOpen() {
  excelBox.value = true;
}
// 请求参数
const requestApi = "/qms/qddetectiondatamain/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  detectionEquipCode: "",
  dataKind: props.dataKind,
  detectionTimes: "",
  startTime: "",
  endTime: "",
};

const deleteParam = {
  api: "/qms/qddetectiondatamain/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/qms/qddetectiondatamain/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开检测数据结果表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改检测数据结果";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增检测数据结果";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开检测数据结果表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "检测数据结果详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/qms/qddetectiondatamain/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}

const formRef = ref(ElForm);
const formData = reactive({
  file: null,
  detectionEquipCode: "",
  partCode: "",
  partBatch: "",
});

const rules = reactive({
  file: [
    { required: true, message: "请选择文件", trigger: "blur" },
  ],
  detectionEquipCode: [
    { required: true, message: "请输入检具编号", trigger: "blur" },
    { max: 50, message: "检具编号长度不能超过50个字符", trigger: "blur" },
  ],
  partCode: [
    { required: true, message: "请输入零件编码", trigger: "blur" },
    { max: 50, message: "零件编码长度不能超过50个字符", trigger: "blur" },
  ],
  partBatch: [
    { required: true, message: "请输入零件批次号", trigger: "blur" },
    { max: 255, message: "零件批次号长度不能超过255个字符", trigger: "blur" },
  ],
});

function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.detectionEquipCode = "";
  formData.partCode = "";
  formData.partBatch = "";
  formData.file = "";
}

const uploadLoading = ref(false);

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  formData.file = file;
}

function upload() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      let config = { headers: { "Content-Type": "multipart/form-data" } };
      const formdata = new FormData();
      formdata.append("detectionEquipCode", formData.detectionEquipCode);
      formdata.append("partCode", formData.partCode);
      formdata.append("partBatch", formData.partBatch);
      formdata.append("file", formData.file);
      formdata.append("dataKind", props.dataKind);
      request
        .post(uploadApi, formdata, config)
        .then((res) => {
          ElMessage({
            type: "success",
            message: "上传成功！",
          });

          excelBox.value = false;
          uploadKey.value = Math.random();
          search();
        })
        .catch((error) => {
          console.log(error);
        });
    }
  });
}

/** 关闭表单弹窗 */
function closeDialog() {
  excelBox.value = false;
  uploadKey.value = Math.random();
  resetForm();
}

function getDate(data: any) {
  if (data) {
    searchParam.value.startTime = data[0];
    searchParam.value.endTime = data[1];
  } else {
    searchParam.value.startTime = "";
    searchParam.value.endTime = "";
  }
}
</script>
